
ConfigPageVars.valueTypes.add("enums", "枚举", function(valueType) {
	// useInItems是否可用于数据字典
	var v = { useInItems:true, metadataOptions:{}, configValueOptions:{}, configValueInit:null };

	// 配置值的初始化处理
	v.configValueInit = function(valueMetadata) {
		if (!valueMetadata) { return; }
		var $configValue = $(this);
		$configValue.xcall("loadData", valueMetadata.items);

		var selections = $configValue.xcall("getValues");
		$.each(selections||[], function(i, selection) {
			var exist = false;
			$.each(valueMetadata.items||[], function(i, value) {
				if (selection == value.key) {
					exist = true; return false;
				}
			});
			if (!exist) { // 如果选中项已被删除, 则清空选中项
				$configValue.xcall("unselect", selection);
			}
		});
	};

	// 配置项的默认值
	v.configValueOptions.formatter = function(data) {
		return data.key + " : " + data.value;
	};
	v.configValueOptions.onChange = function(newValue) {
		var values = $(this).xcall("getData");
		var opts = $(this).xcall("options");
		var text = newValue;
		for (var i = 0; i < values.length; i++) {
			if (values[i].key != newValue) { continue; }
			text = opts.formatter.call(this, values[i]);
			break;
		}
		$(this).closest("form").find(".show-in-type.show-in-" + valueType)
			.find("[textboxname=configText]").xcall("setValue", text);
	};
	// 配置项元数据编辑器
	var doShowFormPanel = function(panel) {
		panel.find(".combo-items").addClass("hide");
		panel.find(".combo-form").removeClass("hide");
		setTimeout(function() {
			panel.find("[textboxname=text]").xcall("focus");
		}, 100);
	};
	var doShowItemsPanel = function(panel) {
		panel.find(".combo-items").removeClass("hide");
		panel.find(".combo-form").addClass("hide");
	};
	v.metadataOptions.onItemChange = function(newItems) {
		var me = $(this);
		var $form = me.closest("form");
		if (me.is("[textboxname=configValue]")) { // 数据字典页面, 枚举作为configValue
			var text = me.xcall("getText");
			var activeLines = $form.find(".show-in-type.show-in-" + valueType);
			var configText = activeLines.find("[textboxname=configText]");
			if (configText.length) {
				configText.xcall("setValue", text);
			} else {
				activeLines.find("[name=configText]").val(text);
			}
		} else { // 配置项页面
			var configValue = $form.find(".show-in-" + valueType).find("input[textboxname=configValue]");
			if (configValue.length == 0) { return; }
			v.configValueInit.call(configValue, { items:newItems, config:me.xcall("getData", "config") });
		}
	};
	v.metadataOptions.onShowPanel = function() {
		var me = $(this);
		var items = me.xcall("getData", "items");
		var panel = me.xcall("panel");
		panel.find(".combo-form form").form("disableValidation");
		if (items.length) {
			doShowItemsPanel(panel);
		} else {
			doShowFormPanel(panel);
		}
	};
	function doElemInit(panel) {
    	var panelOpts = $(this).xcall("options");
    	var space = panelOpts.xref.space;
		space.xui(panel);
	};
	v.metadataOptions.onAfterRenderPanel = doElemInit;
	v.metadataOptions.onAfterRenderItems = doElemInit;
	v.metadataOptions.onBindEvent = function(panel) {
		var self = this;
		// 创建按钮
		panel.on("click", ".combo-items a.do-create", function() {
			doShowFormPanel(panel);
		});
		// 清除按钮
		panel.on("click", ".combo-items a.do-clear", function() {
			$(self).xcall("setValues", { config:undefined, items:[] });
		});
		// 删除按钮
		panel.on("click", ".combo-item a.do-remove", function() {
			var key = $(this).closest(".combo-item").attr("data-key");
			$(self).xcall("removeItem", key);
		});
		// 重置按钮
		panel.on("click", ".combo-form a.do-reset", function() {
			var form = panel.find(".combo-form form");
			var text = $(self).xcall("getText");
			form.find("[textboxname=text]").xcall("setValue", text);
			$(self).xcall("setValues", { config:undefined, items:[] });
		});
		// 保存按钮
		panel.on("click", ".combo-form a.do-save", function() {
			var form = panel.find(".combo-form form");
			form.form("enableValidation");
			if (!form.form("validate")) { return; }
			var text = form.find("[textboxname=text]").xcall("getValue");
			var opts = $(self).xcall("options");
			var items = opts.parseEnumItems.call(self, text);
    		$(self).xcall("addItems", items);
			form.form("reset");
			doShowItemsPanel(panel);
		});
		// 取消按钮
		panel.on("click", ".combo-form a.do-cancel", function() {
			doShowItemsPanel(panel);
		});
	};
	v.metadataOptions.formatter = function(data) {
		var items = data && data.items;
    	if (!items || !items.length) { return ""; }
        var opts = $(this).combocollect("options");
        var buffer = [];
        $.each(items, function(i, v) {
        	buffer.push($.zhh.format('{key} : {value}', v));
        });
        return buffer.join(opts.separator);
	};
	v.metadataOptions.parseEnumItems = function(value, throwOnFormatError) {
		if ($.isArray(value)) { return value; }
		if (value == "") { return []; }
		if (typeof(value) != "string") {
			if (throwOnFormatError) { throw "格式错误: 只支持字符串"; }
			else { return []; }
		}

		var opts = $(this).xcall("options");
		var oldItems = $(this).xcall("getData", "items");

		var idx = 0;
		var keyMaps = {};
		var valueMaps = {};
		if (oldItems && oldItems.length) { // 查找最大序号
			for (var i = 0; i < oldItems.length; i++) {
				var k = oldItems[i].key;
				var v = oldItems[i].value;
				keyMaps[String(k)] = true;
				valueMaps[v] = true;
				if (typeof(k) == number || /^\d+$/.test(k)) {
					var number = parseInt(k);
					if (idx < number) { idx = number; }
				}
			}
			idx ++;
		}
		var newItems = [];
		var collectValidItem = function(item) { // 收集有效的选项
			if (throwOnFormatError) {
				if (!item.key) { throw "格式错误: key为必填项"; }
				if (!item.value) { throw "格式错误: value为必填项"; }
		    	// 校验是否与现有选项冲突
				if (keyMaps[String(item.key)]) { throw "选项key冲突: " + item.key; }
				if (valueMaps[item.value]) { throw "选项value冲突: " + item.value; }
			} else {
				if (!item.key || !item.value || keyMaps[String(item.key)] || valueMaps[item.value]) { 
					return false;
				}
			}
			keyMaps[String(item.key)] = true;
			valueMaps[item.value] = true;
			newItems.push(item);
		};
		if (value.indexOf('{') >= 0 && value.indexOf('}') > 0 && value.indexOf(':') > 0) {
			// JSON格式
			var items = null;
			try {
				var temp = value;
				if (!$.trim(value).startsWith("[")) { temp = "[" + value + "]"; }
				items = (new Function("return " + temp))(); // JSON.parse()的KEY也必须要有引号
			} catch (e) {
			}
			if (items && items.length) {
				for (var i = 0; i < items.length; i++) {
					var item = items[i];
					if (("key" in item) && ("value" in item)) { // { key:"xxx", value:"yyy" }
						collectValidItem(item);
					} else { // { "xxx":"yyy" }
						for (var k in item) {
							collectValidItem({ key:k, value:item[k] });
						}
					}
				}
			}
		} else {
			// 格式1--> MALE:男 | FEMALE:女
			// 格式2--> 男|女 (KEY=从0开始的数字序号)
			var words = value.split(/\r?\n|\|/g);
			for (var i = 0; i < words.length; i++) {
				var word = words[i];
				if ($.trim(word).length == 0) { continue; }
				var loc = word.indexOf(':');
				var item;
				if (loc > 0) {
					item = { key:$.trim(word.substring(0, loc)), value:$.trim(word.substring(loc+1)) };
				} else {
					item = { key:String(idx++), value:$.trim(word) };
				}
				collectValidItem(item);
			}
		}

		return newItems;
	};
	return v;
});


$.extend($.fn.validatebox.defaults.rules, {
	enumsTextValidate: {
		message : "格式错误",
	    validator: function(value, param) {
            var opts = $(this).validatebox("options");
	    	if ($.trim(value) == "") {
        		opts.invalidMessage = "该输入项为必填项";
        		return false;
	    	}

	    	var panelOpts = $(this).closest(".combo-panel").panel("options");
	    	var comboElem = $(panelOpts.comboTarget);
	    	var comboOpts = comboElem.xcall("options");
	    	var parser = comboOpts.parseEnumItems;
	    	try {
	    		var items = parser.call(comboElem, value, true);
	    		if (items && items.length) {
	    			return true;
	    		} else {
	        		opts.invalidMessage = "未找到任何有效的选项";
	        		return false;
	    		}
	    	} catch (e) {
        		opts.invalidMessage = e.toString();
        		return false;
	    	}
	    }
	}
});
